#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Wu Jin'


from flask import render_template, jsonify, request,flash
from flask import Blueprint
from app import db, oid
from flask.ext.login import login_required
from flask import g, redirect, session, url_for
from flask.ext.login import current_user
from app.dao.basedao import *


backend = Blueprint('backend', __name__)

@backend.route('/')
@login_required
def manage():
    if current_user.role != 1:
        return redirect("/index")
    return render_template('admin.html')

@backend.route('/event/')
@backend.route('/event/<string:action>',methods=['GET','POST'])
@login_required
def event(action=None):
    if current_user.role != 1:
        return redirect("/index")
    from app.model import Event
    if action == "delete":
        id = request.values.get("id",None)
        if id:
            delete(Event,id)
            flash("活动 "+id+" 删除成功", "success")
    elif action == "new":
        from app.forms import CreateEventForm
        form = CreateEventForm(request.form)
        if request.method == "GET":
            return render_template('admin/create_event.html',form=form)
        elif request.method == "POST":
            if form.validate_on_submit():
                create(Event,form.data)
                flash("创建活动 %s 成功" % form.data.get("name"), "success")
            else:
                flash(form.errors,"danger")
    event_list = get_all(Event)
    return render_template('admin/event.html',eventList = event_list)


@backend.route('/event/<int:eid>')
@login_required
def event_users(eid):
    if current_user.role != 1:
        return redirect("/index")
    from app.model import Event
    event = get_by_attr(Event,dict(id=eid))
    return render_template('admin/event_user.html',event = event)


@backend.route('/user')
@backend.route('/user/<string:action>',methods=['GET','POST'])
@login_required
def users(action=None):
    if current_user.role != 1:
        return redirect("/index")
    from app.model import User
    if action == "delete":
        id = request.values.get("id",None)
        if id:
            delete(User,id)
            flash("小组 "+id+" 删除成功", "success")
    elif action == "new":
        from app.forms import CreateUserForm
        form = CreateUserForm(request.form)
        if request.method == "GET":
            return render_template('admin/create_user.html',form=form)
        elif request.method == "POST":
            if form.validate_on_submit():
                create(User,form.data)
                flash("创建小组 %s 成功" % form.data.get("name"), "success")
            else:
                flash(form.errors,"danger")
    from app.model import User
    user_list = get_all(User)
    return render_template('admin/user.html',userList = user_list)